package com.blackwatchplaid;

// Simple text processing utility functions. I'm scared of j2me XML parsers.
class GhettoParseHTMLUtils {
    // returns true if it is a non-printable or control character
    // e.g. isBad('\r') => true
    static public boolean isBad(char c) {
        return c<' ';
    }
    // trims, strips out bad characters, collapses whitespace
    // e.g. trimAndCollapse("   Gnarls   \rBarley") => "Gnarls Barkley"
    static public String trimAndCollapse(String txt) {
        txt = txt.trim();
        String r = null;
        boolean lastWasSpace=false;
        boolean skipping = false;
        int lastGood = 0;
        for (int i=0; i<txt.length(); ++i) {
            char c = txt.charAt(i);
            if (isBad(c) || (c==' ' && lastWasSpace)) {
                if (r==null) r = txt.substring(0, i);
                continue;
            }else if (c==' ') {
                lastWasSpace = true;
            } else {
                lastWasSpace = false;
            }
            if (r!=null)
                r += c;
        }
        return r==null?txt:r;
    }
    
    static public String replaceAll(String html, String search, String replace) {
        // need faster non-recursive algorithm
        int i=html.indexOf(search);
        if (i==-1 || search.length()==0)
            return html;
        else
            return html.substring(0,i)+replace+replaceAll(html.substring(i+search.length()),search,replace);
    }
    static public String unescapeHTML(String html) {
        // sure needs work and optimization
        return replaceAll(html, "&amp;", "&");
    }
    static public int readNumber(String html, int start) {
        int n = 0;
        while (Character.isDigit(html.charAt(start))) {
            n=n*10+(html.charAt(start++)-'0');
        }
        return n;
    }
    static public int lastIndexOf(String html, String search, int fromIndex) {
        // need faster algorithm
        if (search.length()==0 || html.length()==0)
            return -1;
        int i=fromIndex+1-search.length();
        while (i>=0) {
            if (html.startsWith(search, i))
                return i;
            if (i==0)
                break;
            i = html.lastIndexOf(search.charAt(0),i-1);
        }
        return -1;
    }
    static public int lastIndexOf(String html, String search) {
        return lastIndexOf(html, search, html.length()-1);
    }
}
